from django.shortcuts import render

# Create your views here.


from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
import string,random,base64

from django.core.cache import cache
from django.core.signing import Signer
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
from .models import User,Item
from datetime import timedelta

# 天天开心啊你要
# 判断是否为空
def is_empty(c):
    return c is None or str(c).strip()==''


def createtoken(name):

    randomstr = ''.join(random.choices(string.ascii_letters,k=8))
    token = Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token

def checktoken(request):

    gettoken = request.META.get('HTTP_TOKEN')
    if gettoken is None:
        return False,'XXXX'
    unsigntoken = Signer().unsign(gettoken)
    name = unsigntoken[8:]
    checktoken = cache.get(f'test_{name}')
    if checktoken is None:
        return False,'XXXX'
    return name

# 加密
def base64node(c):
    bc = bytes(c,encoding='utf-8')
    bc64 = base64.b64encode(bc).decode('utf-8')
    return bc64

# 用户注册
@api_view(['POST'])
def register(request):

    data = JSONParser().parse(request)
    username = data.get('username')
    password = data.get('password')

    # 参数：username（必填，用户名），password（必填，密码）
    if is_empty(username) or is_empty(password):
        return JsonResponse({
            'message':'必填参数不能为空'
        },status=400)

    # 注册新用户，用户名需唯一
    obj = User.objects.filter(username=username)
    if obj.exists() is True:
        return JsonResponse({
            'message':'用户名已存在,用户名需唯一'
        },status=400)
    pwd = base64node(password)
    User(username=username,password=pwd).save()
    datalist  = []
    for item in obj:

        datalist.append({
            'username':item.username,
            'password':item.password,
        })

    return JsonResponse({
        'message':'注册成功',
        'data':data
    })


# 登录
@api_view(['POST'])
def login(request):

    data = JSONParser().parse(request)
    username = data.get('username')
    password = data.get('password')
    if is_empty(username) or is_empty(password):
        return JsonResponse({
            'message':'必填参数不能为空'
        },status=400)

    obj = User.objects.get(username=username)
    pwd = base64node(password)
    if obj.password==pwd:
        token = createtoken(username)
        return JsonResponse({
            'message':'登录成功',
            'token':token
        })


# 物品发布
@api_view(['POST'])
def addpublish(request):


    data = JSONParser().parse(request)
    title = data.get('title')
    price = data.get('price')
    seller_id = data.get('seller_id')

    if is_empty(title) or is_empty(price):
        return JsonResponse({
            'message':'必填参数不能为空'
        },status=400)

    Item(title=title,price=price,seller_id_id=seller_id).save()
    return JsonResponse({
        'message':'物品发布成功'
    })


